<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>转账</title>
  <style>
    .container {
      width: 50%;
      margin: 50px auto;
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }
    .form-group {
      margin-bottom: 20px;
    }
    label {
      display: block;
      margin-bottom: 8px;
      color: #333;
    }
    select, input, textarea {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      box-sizing: border-box;
    }
    textarea {
      height: 80px;
      resize: vertical;
    }
    .btn {
      background-color: #2c6ecb;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
    }
    .back-btn {
      display: inline-block;
      margin-top: 20px;
      color: #2c6ecb;
      text-decoration: none;
    }
    .message {
      margin-top: 15px;
      padding: 10px;
      border-radius: 4px;
    }
    .success {
      color: #4CAF50;
      background-color: #E8F5E9;
      border: 1px solid #4CAF50;
    }
    .error {
      color: #F44336;
      background-color: #FFEBEE;
      border: 1px solid #F44336;
    }
    .transfer-details {
      margin-top: 10px;
      padding: 10px;
      background-color: #f9f9f9;
      border-left: 4px solid #4CAF50;
    }
    .detail-row {
      display: flex;
      margin-bottom: 5px;
    }
    .detail-label {
      font-weight: bold;
      width: 120px;
    }
    .detail-value {
      flex-grow: 1;
    }
  </style>
</head>
<body>
<div class="container">
  <h3>转账操作</h3>
  <form id="transferForm" action="/transfer" method="post">
    <div class="form-group">
      <label for="fromAccountId">转出账户</label>
      <select id="fromAccountId" name="fromAccountId" required>
        <option value="">-- 请选择转出账户 --</option>
      </select>
    </div>
    <div class="form-group">
      <label for="toAccountId">转入账户</label>
      <select id="toAccountId" name="toAccountId" required>
        <option value="">-- 请选择转入账户 --</option>
      </select>
    </div>
    <div class="form-group">
      <label for="amount">转账金额</label>
      <input type="number" step="0.01" min="0.01" id="amount" name="amount" required>
    </div>
    <div class="form-group">
      <label for="remark">备注（可选）</label>
      <textarea id="remark" name="remark"></textarea>
    </div>
    <button type="submit" class="btn">确认转账</button>
  </form>
  <div class="message" id="message">${message}</div>
  <a href="/main" class="back-btn">返回功能页</a>
</div>

<script>
  // 页面加载完成后获取账户列表
  document.addEventListener('DOMContentLoaded', function() {
    fetch('/accounts')
            .then(response => response.json())
            .then(data => {
              if (data.code === 2000) {
                populateAccountSelect('fromAccountId', data.data);
                populateAccountSelect('toAccountId', data.data);
              } else {
                showMessage('加载账户列表失败: ' + data.msg, 'error');
              }
            })
            .catch(error => {
              showMessage('加载账户列表时出错: ' + error, 'error');
            });
  });

  // 填充账户下拉框
  function populateAccountSelect(selectId, accounts) {
    const select = document.getElementById(selectId);
    accounts.forEach(account => {
      const option = document.createElement('option');
      option.value = account.accountId;
      option.textContent = `${account.accountId} (余额: ${account.balance}元)`;
      select.appendChild(option);
    });
  }

  // 显示消息
  function showMessage(msg, type) {
    const messageDiv = document.getElementById('message');
    messageDiv.textContent = msg;
    messageDiv.className = 'message ' + type;
  }

  // 显示转账详情
  function showTransferDetails(details) {
    // 先移除之前可能存在的详情
    const oldDetails = document.getElementById('transferDetails');
    if (oldDetails) {
      oldDetails.remove();
    }

    // 创建新的详情区域
    const messageDiv = document.getElementById('message');
    const detailsDiv = document.createElement('div');
    detailsDiv.id = 'transferDetails';
    detailsDiv.className = 'transfer-details';

    // 添加详情行
    const addDetailRow = (label, value) => {
      const row = document.createElement('div');
      row.className = 'detail-row';

      const labelElement = document.createElement('div');
      labelElement.className = 'detail-label';
      labelElement.textContent = label;

      const valueElement = document.createElement('div');
      valueElement.className = 'detail-value';
      valueElement.textContent = value;

      row.appendChild(labelElement);
      row.appendChild(valueElement);
      detailsDiv.appendChild(row);
    };

    // 添加各详情项
    addDetailRow('交易状态:', details.status);
    addDetailRow('转出账户:', details.fromAccountId);
    addDetailRow('转入账户:', details.toAccountId);
    addDetailRow('转账金额:', `${details.amount}元`);
    addDetailRow('交易时间:', details.transactionTime);
    if (details.remark) {
      addDetailRow('备注:', details.remark);
    }

    // 插入到消息后面
    messageDiv.insertAdjacentElement('afterend', detailsDiv);
  }

  // 表单提交处理
  document.getElementById('transferForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const fromAccountId = document.getElementById('fromAccountId').value;
    const toAccountId = document.getElementById('toAccountId').value;
    const amount = document.getElementById('amount').value;
    const remark = document.getElementById('remark').value;

    if (!fromAccountId || !toAccountId || !amount) {
      showMessage('请填写完整信息', 'error');
      return;
    }

    if (fromAccountId === toAccountId) {
      showMessage('转出账户和转入账户不能相同', 'error');
      return;
    }

    if (parseFloat(amount) <= 0) {
      showMessage('转账金额必须大于0', 'error');
      return;
    }

    fetch('/transfer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        fromAccountId: fromAccountId,
        toAccountId: toAccountId,
        amount: amount,
        remark: remark
      })
    })
            .then(response => response.json())
            .then(data => {
              if (data.code === 2000) {
                showMessage('转账成功', 'success');

                // 显示转账详情
                showTransferDetails({
                  status: '成功',
                  fromAccountId: fromAccountId,
                  toAccountId: toAccountId,
                  amount: amount,
                  fromBeforeBalance: data.data.fromBeforeBalance,
                  fromAfterBalance: data.data.fromAfterBalance,
                  toBeforeBalance: data.data.toBeforeBalance,
                  toAfterBalance: data.data.toAfterBalance,
                  transactionTime: new Date().toLocaleString(),
                  remark: remark || '无'
                });

                // 清空表单
                document.getElementById('transferForm').reset();

                // 重新加载账户列表
                setTimeout(() => {
                  fetch('/accounts')
                          .then(response => response.json())
                          .then(data => {
                            if (data.code === 2000) {
                              // 更新下拉框选项
                              const fromSelect = document.getElementById('fromAccountId');
                              const toSelect = document.getElementById('toAccountId');
                              fromSelect.innerHTML = '<option value="">-- 请选择转出账户 --</option>';
                              toSelect.innerHTML = '<option value="">-- 请选择转入账户 --</option>';
                              populateAccountSelect('fromAccountId', data.data);
                              populateAccountSelect('toAccountId', data.data);
                            }
                          });
                }, 1000);
              } else {
                showMessage('转账失败: ' + data.msg, 'error');
              }
            })
            .catch(error => {
              showMessage('转账时出错: ' + error, 'error');
            });
  });
</script>
</body>
</html>